<template>
  <div class="m-count-line" :class="comClazz">
    <MCountLineItem
      v-for="(i, index) in color"
      :key="index"
      :round="round"
      :color="i"
      :width="getItemWidth(index)"
    >
    </MCountLineItem>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, PropType } from "vue";
import MCountLineItem from "./MCountLineItem.vue";
export default defineComponent({
  name: "MCountLine",
  components: {
    MCountLineItem,
  },
  props: {
    count: {
      type: Array as PropType<Array<number>>,
      default: () => [],
      required: true,
    },
    color: {
      type: Array,
      default: () => [],
    },
    round: {
      type: Boolean,
      default: false,
    },
    reverse: {
      type: Boolean,
      default: false,
    },
  },

  setup(props) {
    const total = computed(() => {
      if (props.count.length === 0) {
        return 0;
      }
      return props.count.reduce<number>((memo, cur) => {
        if (!cur) {
          memo += 0;
        } else {
          memo += Number(cur);
        }
        return memo;
      }, 0);
    });
    const getItemWidth = (index: number): string => {
      const itemCount = props.count[index];
      if (!itemCount) {
        return "0";
      }
      return ((itemCount / total.value) * 100).toFixed(2) + "%";
    };

    const comClazz = computed(() => {
      return {
        "is-round": props.round,
        "is-reverse": props.reverse,
      };
    });

    return {
      total,
      getItemWidth,
      comClazz,
    };
  },
});
</script>
